<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JavaScript," />










<meta name="description" content="一、概述在JavaScript中，数组是数据类型中非常重要的一环。所传入的数据一般也都需要转化为数组，然后通过数组所提供的API来对数据进行处理，当然它可能本身传来的就是数组。此外，在函数式编程中，数组也提供了不少的API来帮助我们实现函数式编程，从而使代码变得更为可读，因此对数组的一些操作进行一个总结还是很有必要的。 由于在JavaScript中，数组的API还是挺多的，因此本文将主要讨论一些常">
<meta name="keywords" content="JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript数据处理之数组操作">
<meta property="og:url" content="http://srtian96.gitee.io/blog/2018/12/09/JavaScript数据处理之数组操作/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="一、概述在JavaScript中，数组是数据类型中非常重要的一环。所传入的数据一般也都需要转化为数组，然后通过数组所提供的API来对数据进行处理，当然它可能本身传来的就是数组。此外，在函数式编程中，数组也提供了不少的API来帮助我们实现函数式编程，从而使代码变得更为可读，因此对数组的一些操作进行一个总结还是很有必要的。 由于在JavaScript中，数组的API还是挺多的，因此本文将主要讨论一些常">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://images.gitee.com/uploads/images/2018/1209/181116_7e7cdfaa_1575229.png">
<meta property="og:image" content="https://images.gitee.com/uploads/images/2018/1209/182525_96336504_1575229.png">
<meta property="og:updated_time" content="2018-12-09T11:03:35.516Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaScript数据处理之数组操作">
<meta name="twitter:description" content="一、概述在JavaScript中，数组是数据类型中非常重要的一环。所传入的数据一般也都需要转化为数组，然后通过数组所提供的API来对数据进行处理，当然它可能本身传来的就是数组。此外，在函数式编程中，数组也提供了不少的API来帮助我们实现函数式编程，从而使代码变得更为可读，因此对数组的一些操作进行一个总结还是很有必要的。 由于在JavaScript中，数组的API还是挺多的，因此本文将主要讨论一些常">
<meta name="twitter:image" content="https://images.gitee.com/uploads/images/2018/1209/181116_7e7cdfaa_1575229.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/2018/12/09/JavaScript数据处理之数组操作/"/>





  <title>JavaScript数据处理之数组操作 | Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/12/09/JavaScript数据处理之数组操作/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JavaScript数据处理之数组操作</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-12-09T18:28:19+08:00">
                2018-12-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,681
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  11
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="一、概述"><a href="#一、概述" class="headerlink" title="一、概述"></a>一、概述</h2><p>在JavaScript中，数组是数据类型中非常重要的一环。所传入的数据一般也都需要转化为数组，然后通过数组所提供的API来对数据进行处理，当然它可能本身传来的就是数组。此外，在函数式编程中，数组也提供了不少的API来帮助我们实现函数式编程，从而使代码变得更为可读，因此对数组的一些操作进行一个总结还是很有必要的。</p>
<p>由于在JavaScript中，数组的API还是挺多的，因此本文将主要讨论一些常用的API：</p>
<ul>
<li>Array.join</li>
<li>Array.slice</li>
<li>Array.sort</li>
<li>Array.forEach</li>
<li>Array.map</li>
<li>Array.filter</li>
<li>Array.reduce</li>
</ul>
<p>其中Array.map、Array.filter、Array.reduce都是高阶函数。</p>
<h2 id="二、数组操作"><a href="#二、数组操作" class="headerlink" title="二、数组操作"></a>二、数组操作</h2><h3 id="2-1-Array-join"><a href="#2-1-Array-join" class="headerlink" title="2.1 Array.join()"></a>2.1 Array.join()</h3><p> Array.join()是个非常简单的API，该方法将一个数组（或一个类数组对象）的所有元素连接成一个字符串并返回这个字符串。具体用法如下：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line">a.join(<span class="string">'-'</span>) <span class="comment">// "1-2-3"</span></span><br></pre></td></tr></table></figure></p>
<p>其中join的工作其实很简单：即遍历数组，并将数组中的每一个元素都与传入的参数相加。模拟起来大致的运行流程就是这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.prototype.join = <span class="function"><span class="keyword">function</span>(<span class="params">char</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">let</span> result = <span class="keyword">this</span>[<span class="number">0</span>] || <span class="string">''</span></span><br><span class="line">  <span class="keyword">let</span> len = <span class="keyword">this</span>.length</span><br><span class="line">  <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">1</span>; i &lt; len; i++)&#123;</span><br><span class="line">      result += char + <span class="keyword">this</span>[i]</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> result</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此外，join()也能连接类数组：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params">a, b, c</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> s = <span class="built_in">Array</span>.prototype.join.call(<span class="built_in">arguments</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(s);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">f(<span class="number">1</span>, <span class="string">'a'</span>, <span class="literal">true</span>)  <span class="comment">// '1,a,true'</span></span><br></pre></td></tr></table></figure>
<h3 id="2-2-Array-slice"><a href="#2-2-Array-slice" class="headerlink" title="2.2 Array.slice"></a>2.2 Array.slice</h3><p>Array.slice(beginIndex, endIndex) 方法返回一个新的数组对象，这一对象是一个由 begin 和 end（不包括end）决定的原数组的浅拷贝,且原始数组不会被改变：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> fruits = [<span class="string">'Banana'</span>, <span class="string">'Orange'</span>, <span class="string">'Lemon'</span>, <span class="string">'Apple'</span>, <span class="string">'Mango'</span>]</span><br><span class="line"><span class="keyword">let</span> citrus = fruits.slice(<span class="number">1</span>, <span class="number">3</span>) <span class="comment">// ['Orange','Lemon']</span></span><br></pre></td></tr></table></figure>
<p>它的用法也很简单，因此在ES6出现之前，很多人都用它来讲类数组装化为数组：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">array = <span class="built_in">Array</span>.prototye.slice.call(arrayLike)</span><br><span class="line"><span class="comment">// or</span></span><br><span class="line">array = [].slice.call(arrayLike)</span><br></pre></td></tr></table></figure></p>
<p>所以仔细想想Array.slice()的套路大概就是这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.prototype.slice = <span class="function"><span class="keyword">function</span>(<span class="params">begin, end</span>)</span>&#123;</span><br><span class="line">    begin = begin || <span class="number">0</span></span><br><span class="line">    end = end || <span class="keyword">this</span>.length</span><br><span class="line">    <span class="keyword">let</span> result = []</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> i = begin; i &lt; end; i++)&#123;</span><br><span class="line">        result.push(<span class="keyword">this</span>[i])</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当然了，使用此方法来将类数组转化为数组非常的不优雅，因此ES6又提供了Array.from来讲类数组转化为数组：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = array.from(arrayLike)</span><br></pre></td></tr></table></figure>
<h3 id="2-3-Array-sort"><a href="#2-3-Array-sort" class="headerlink" title="2.3 Array.sort"></a>2.3 Array.sort</h3><p>Array.sort([callback])也是数组操作中常用的一个API，其内置的排序算法主要是快速排序和插入排序的混合，当数组长度低于11个的时候就是用插入排序，除此之外就使用快排。具体代码可以直接去看源码：</p>
<blockquote>
<p>github.com/v8/v8/blob/master/src/js/array.js#L718</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">InnerArraySort</span>(<span class="params">array, length, comparefn</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// In-place QuickSort algorithm.</span></span><br><span class="line">  <span class="comment">// For short (length &lt;= 10) arrays, insertion sort is used for efficiency.</span></span><br><span class="line">  <span class="keyword">if</span> (!IS_CALLABLE(comparefn)) &#123;</span><br><span class="line">    comparefn = <span class="function"><span class="keyword">function</span> (<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (x === y) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">      <span class="keyword">if</span> (%_IsSmi(x) &amp;&amp; %_IsSmi(y)) &#123;</span><br><span class="line">        <span class="keyword">return</span> %SmiLexicographicCompare(x, y);</span><br><span class="line">      &#125;</span><br><span class="line">      x = TO_STRING(x);</span><br><span class="line">      y = TO_STRING(y);</span><br><span class="line">      <span class="keyword">if</span> (x == y) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">return</span> x &lt; y ? <span class="number">-1</span> : <span class="number">1</span>;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注释也说的很清楚，默认使用快速排序，但是当数组长度小于11的数组，使用的是插入排序。这也符合我们的正常观点，因为插入排序在数组长度小于一定值的时候是会比快速排序速度更快，而快速排序在大规模数据的时候则更有优势。插入排序是稳定的，快速排序是不稳定的。当然这在不同的浏览器引擎中的表现是不同的，比如在火狐浏览器中使用的则是归并排序。</p>
<p>那么我们一般如何使用它呢？首先它的语法是这样的：Array.sort([callback])。也就是说我们可用通过定制callback也就是回调函数来定义如何对数组里的元素进行排序。但获取有些小老弟会发现sort有这么一个很有意思的特性，这也是我早期学JavaScript时，碰到的一个很有意思的问题：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> numbers1 = [<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">2</span>, <span class="number">4</span>]</span><br><span class="line">numbers1.sort()</span><br><span class="line"><span class="built_in">console</span>.log(numbers1) <span class="comment">// [1, 2, 3, 4, 5]</span></span><br><span class="line"><span class="comment">// 还有这样的</span></span><br><span class="line"><span class="keyword">let</span> numbers2 = [<span class="number">1</span>, <span class="number">15</span>, <span class="number">20</span>, <span class="number">4</span>, <span class="number">3</span>]</span><br><span class="line">numbers2.sort()</span><br><span class="line"><span class="built_in">console</span>.log(numbers2) <span class="comment">// [1, 15, 20, 3, 4]</span></span><br></pre></td></tr></table></figure>
<p>我们可以看到，同样是调用sort()方法，但上下两个数组所得到的结果完全不同。其实其根本原因在于sort方法执行的时候，数组的每个元素会先执行一次 toString() 方法，然后在根据字符串的 Unicode 编码进行排序。因此我们在使用sort的时候就需要定义相应的callback，来达到排序的目的，比如最常见的升序排序：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = [<span class="number">1</span>, <span class="number">23</span>, <span class="number">5</span>, <span class="number">12</span>, <span class="number">4</span>]</span><br><span class="line">a.sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> a - b)</span><br><span class="line">consloe.log(a) <span class="comment">// [1, 4, 5, 12, 23]</span></span><br></pre></td></tr></table></figure>
<p>其计算规则很简单：</p>
<ul>
<li>如果 a - b 小于 0 ，那么 a 在 b 的前面，也就是会按照升序排列</li>
<li>如果 a - b 等于 0 ，那么 a 和 b 的位置保持不变（相对的，视具体算法而变）</li>
<li>如果 a - b 大于 0 ，那么 b 在 a 的前面，也就是会按照降序排列</li>
</ul>
<p>当然我们也不局限如此，我们经常碰到的数据可能不局限于单纯的数字数组，比如我在一次面试时，面试官就给了我这么一串数据：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[&#123;<span class="attr">order</span>: <span class="number">3</span>&#125;,&#123;<span class="attr">order</span>: <span class="number">4</span>&#125;,&#123;<span class="attr">order</span>: <span class="number">2</span>&#125;,&#123;<span class="attr">order</span>: <span class="number">100</span>&#125;]</span><br></pre></td></tr></table></figure>
<p>让我将其根据order的值从大到小进行排序。既然而然我们就能使用sort来对其进行排序了：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> order = [&#123;<span class="attr">order</span>: <span class="number">3</span>&#125;,&#123;<span class="attr">order</span>: <span class="number">4</span>&#125;,&#123;<span class="attr">order</span>: <span class="number">2</span>&#125;,&#123;<span class="attr">order</span>: <span class="number">100</span>&#125;]</span><br><span class="line"><span class="keyword">var</span> result = order.sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> b.order - a.order)</span><br></pre></td></tr></table></figure>
<p>这样就能实现我们预期的效果了，是不是很强大、很简单~</p>
<h3 id="2-4-Array-forEach"><a href="#2-4-Array-forEach" class="headerlink" title="2.4 Array.forEach"></a>2.4 Array.forEach</h3><p>forEach这个API在我们日常开发中也很有用（当然其实我个人认为在map出来后可以使用map来代替forEach,这个在后面说为啥），它可以对数组的每一个元素都进行操作，比如这样：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line">a.forEach(<span class="function">(<span class="params">item</span>) =&gt;</span> <span class="built_in">console</span>.log(item + <span class="number">1</span>))</span><br><span class="line"><span class="comment">// 2 3 4</span></span><br></pre></td></tr></table></figure></p>
<p>它的大致实现思路就像这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.prototype.forEach = <span class="function"><span class="keyword">function</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>, len = <span class="keyword">this</span>.length; i &lt; len ; i++) &#123;</span><br><span class="line">         fn.apply(<span class="keyword">this</span>, [<span class="keyword">this</span>[i], i, <span class="keyword">this</span>])</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>因此总的来说，forEach与我们常用的for循环在功能上存在重叠，也在一定程度上可以替代for循环的一些功能，但需要注意的是，它与for循环还是存在以下一些差异：</p>
<ul>
<li>forEach 没法 break</li>
<li>forEach 用到了函数，因此每次迭代都会产生一个新的函数作用域；而 for 循环只有一个作用域</li>
</ul>
<h3 id="2-5-Array-map"><a href="#2-5-Array-map" class="headerlink" title="2.5 Array.map"></a>2.5 Array.map</h3><p>map()方法在功能上和forEach相差不大，但由于它本身存在返回值，且调用起来也更为方便，代码可读性也更高，因此推荐使用map：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>]</span><br><span class="line"><span class="keyword">let</span> b = a.map(<span class="function">(<span class="params">item</span>) =&gt;</span> item + <span class="number">1</span>)</span><br><span class="line"><span class="built_in">console</span>.log(b)</span><br></pre></td></tr></table></figure></p>
<p>同时，在函数式编程中，使用map保证存在一个返回值也是达到链式编程的一个重要的基础。map大概的代码逻辑应该是这样的：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.prototype.map = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> result = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>, len = <span class="keyword">this</span>.length; i &lt; len; i++) &#123;</span><br><span class="line">         result[i] = fn.apply(<span class="keyword">this</span>, [<span class="keyword">this</span>[i], i, <span class="keyword">this</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="2-6-Array-filter"><a href="#2-6-Array-filter" class="headerlink" title="2.6 Array.filter"></a>2.6 Array.filter</h3><p>filter() 方法创建一个包含所有通过测试的元素的新数组。我们通常使用filter()来对数组进行筛选，挑选出我们需要的元素，同时也可以使用代码更具有可读性：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> prices = [<span class="number">25</span>, <span class="number">30</span>, <span class="number">15</span>, <span class="number">55</span>, <span class="number">40</span>, <span class="number">10</span>]</span><br><span class="line">prices.filter(<span class="function">(<span class="params">item</span>) =&gt;</span> item &gt;= <span class="number">30</span>)</span><br><span class="line"><span class="comment">// [30, 55, 40]</span></span><br></pre></td></tr></table></figure></p>
<p>同样的，作为函数式编程重要的一员，filter同样也不会对原有的数组产生影响，而是产生一个新的数组，从而达到链式调用的目的，因此我们就可以猜想它的实现逻辑大致就是下面这样的：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Arra.prototype.filter = <span class="function"><span class="keyword">function</span>(<span class="params">fn</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> result = []</span><br><span class="line">    <span class="keyword">let</span> temp</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i=<span class="number">0</span>; i&lt;<span class="keyword">this</span>.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span>(i <span class="keyword">in</span> <span class="keyword">this</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (temp = fn.call(<span class="literal">undefined</span>, <span class="keyword">this</span>[i], i, <span class="keyword">this</span>)) &#123;</span><br><span class="line">                result.push(<span class="keyword">this</span>[i])</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="2-7-Array-reduce"><a href="#2-7-Array-reduce" class="headerlink" title="2.7 Array.reduce"></a>2.7 Array.reduce</h3><p>Array.reduce(callback,[initialValue])方法对累计器和数组中的每个元素（从左到右）应用一个函数，将其简化为单个值。它接受四个参数:</p>
<ul>
<li>Accumulator (acc) (累计器)</li>
<li>Current Value (cur) (当前值)</li>
<li>Current Index (idx) (当前索引)</li>
<li>Source Array (src) (源数组)</li>
</ul>
<p>执行起来就是这样的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>].reduce(<span class="function"><span class="keyword">function</span>(<span class="params">accumulator, currentValue, currentIndex, array</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> accumulator + currentValue;</span><br><span class="line">&#125;) <span class="comment">// 10</span></span><br></pre></td></tr></table></figure>
<p>reduce的功能非常强大，它同样也可以模拟map以及filter，比如模拟map:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> array = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>]</span><br><span class="line"><span class="keyword">let</span> array1 = array.map(<span class="function">(<span class="params">v</span>) =&gt;</span> v+<span class="number">1</span>)</span><br><span class="line"><span class="comment">//用reduce实现为：</span></span><br><span class="line"><span class="keyword">let</span> array2 = array.reduce(<span class="function">(<span class="params">result, v</span>)=&gt;</span> &#123;</span><br><span class="line">     result.push(v + <span class="number">1</span>)</span><br><span class="line">     <span class="keyword">return</span> result</span><br><span class="line"> &#125;,[ ])</span><br></pre></td></tr></table></figure></p>
<p>同样我们也能来模拟filter:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> array1 = array.filter( <span class="function">(<span class="params">v</span>) =&gt;</span> v % <span class="number">2</span> === <span class="number">0</span> )</span><br><span class="line"><span class="comment">//用reduce实现为：</span></span><br><span class="line"><span class="keyword">let</span> array2 = array.reduce(<span class="function">(<span class="params">result, v</span>) =&gt;</span> &#123;</span><br><span class="line">     <span class="keyword">if</span>(v % <span class="number">2</span> === <span class="number">0</span>)&#123;</span><br><span class="line">        result.push(v)</span><br><span class="line">        &#125;</span><br><span class="line">     <span class="keyword">return</span> result</span><br><span class="line"> &#125;, [])</span><br></pre></td></tr></table></figure>
<p>是不是很有意思~ 当然平常开发的时候别这么做，因为使用指定的API来完成指定的任务会让代码变得更可读，更以维护~</p>
<h2 id="三、关于高阶函数的性能"><a href="#三、关于高阶函数的性能" class="headerlink" title="三、关于高阶函数的性能"></a>三、关于高阶函数的性能</h2><p>关于函数式编程最近在社区发生了很多的讨论。以我个人的看法，函数式编程在开发一些普通的应用或当应用变大时，其声明式的、纯函数式的，都为项目代码的可维护性以及可读性提供了很好的支持，这也是react最近出来的hooks以及redux还有Rx.js如此火爆的原因。但同时，我们也应该更具具体情况来考虑使用怎样的编程方式，比如我们在解决一些CV或较为底层的开发的时候，函数式编程可能就不能满足我们的开发需求，毕竟函数式编程在性能方面还是有所缺失的，比如在上面所说的那些高阶函数与原生for循环之间在性能上区别:</p>
<blockquote>
<p><a href="https://jsperf.com/for-foreach-reduce" target="_blank" rel="noopener">https://jsperf.com/for-foreach-reduce</a><br><img src="https://images.gitee.com/uploads/images/2018/1209/181116_7e7cdfaa_1575229.png" alt="输入图片说明" title="捕获.PNG"></p>
</blockquote>
<p>还有forEach、for、reduce之间的性能差距：</p>
<p><img src="https://images.gitee.com/uploads/images/2018/1209/182525_96336504_1575229.png" alt="输入图片说明" title="性能2.PNG"></p>
<p>可以看到，虽然浏览器引擎已经对这些高阶函数进行了优化，但比起原生的for循环这些高阶函数的执行效率还是有所差别的~因此在使用函数式编程的时候还是需要考虑项目实际的需要，当然我个人认为只要不是对性能要求非常严格的情况都可以使用函数式编程来增加我们写的代码的可读性和可维护性。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/JavaScript/" rel="tag"># JavaScript</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/12/01/JavaScript字符串的处理/" rel="next" title="JavaScript数据处理之字符串">
                <i class="fa fa-chevron-left"></i> JavaScript数据处理之字符串
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/12/17/关于2018，我有这些想谈谈的/" rel="prev" title="关于2018，我有这些想谈谈的">
                关于2018，我有这些想谈谈的 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、概述"><span class="nav-number">1.</span> <span class="nav-text">一、概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、数组操作"><span class="nav-number">2.</span> <span class="nav-text">二、数组操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-Array-join"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 Array.join()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-Array-slice"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 Array.slice</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-Array-sort"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 Array.sort</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-Array-forEach"><span class="nav-number">2.4.</span> <span class="nav-text">2.4 Array.forEach</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-5-Array-map"><span class="nav-number">2.5.</span> <span class="nav-text">2.5 Array.map</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-6-Array-filter"><span class="nav-number">2.6.</span> <span class="nav-text">2.6 Array.filter</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-7-Array-reduce"><span class="nav-number">2.7.</span> <span class="nav-text">2.7 Array.reduce</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、关于高阶函数的性能"><span class="nav-number">3.</span> <span class="nav-text">三、关于高阶函数的性能</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
